package com.chatdating.service;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class BaiduFaceService {

    private static final String TOKEN_URL = "https://aip.baidubce.com/oauth/2.0/token";
    private static final ObjectMapper objectMapper = new ObjectMapper();

    // 缓存 access_token 及其过期时间
    private String cachedToken;
    private long tokenExpireTime;

    /**
     * 获取 access_token（带缓存和JSON解析）
     */
    public synchronized String getAccessToken(String clientId, String clientSecret) throws IOException {
        // 如果缓存中的 token 未过期，直接返回
        if (cachedToken != null && System.currentTimeMillis() < tokenExpireTime) {
            return cachedToken;
        }

        // 请求新 token
        String params = String.format("grant_type=client_credentials&client_id=%s&client_secret=%s",
                clientId, clientSecret);

        try (CloseableHttpClient httpClient = HttpClients.createDefault();
             CloseableHttpResponse response = httpClient.execute(new HttpPost(TOKEN_URL + "?" + params))) {

            HttpEntity entity = response.getEntity();
            if (entity == null) {
                throw new RuntimeException("HTTP 响应为空");
            }

            String jsonResponse = EntityUtils.toString(entity);
            JsonNode jsonNode = objectMapper.readTree(jsonResponse);

            if (jsonNode.has("error")) {
                throw new RuntimeException("获取 access_token 失败: " + jsonResponse);
            }

            String accessToken = jsonNode.get("access_token").asText();
            int expiresIn = jsonNode.get("expires_in").asInt();

            // 更新缓存
            this.cachedToken = accessToken;
            this.tokenExpireTime = System.currentTimeMillis() + expiresIn * 1000L;

            return accessToken;
        }
    }


// 向百度API发送POST请求
    public String sendHttpPostRequest(String url, String jsonBody1 ,String jsonBody2) throws IOException {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);

        ObjectMapper mapper = new ObjectMapper();

        List<Map<String, String>> jsonArray = new ArrayList<>();
        jsonArray.add(mapper.readValue(jsonBody1, Map.class));
        jsonArray.add(mapper.readValue(jsonBody2, Map.class));

        String validJsonArray = mapper.writeValueAsString(jsonArray);



        httpPost.setHeader("Content-Type", "application/json");
        httpPost.setEntity(new org.apache.http.entity.StringEntity(validJsonArray, "UTF-8"));

        try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                return EntityUtils.toString(entity, "UTF-8");
            }
        }
        return null;
    }
}


